/* ----------------------------------------------------------------------------------------------------------------------------------------------- /

Facade - 类名称
修改许可权限 - 江利峰

< --- Public Vars ------------------------------------------------------------------------------------------------------------------------------ >

< --- Public Functions ------------------------------------------------------------------------------------------------------------------------ >

※ 构造函数
public function Facade()

/ ----------------------------------------------------------------------------------------------------------------------------------------------- */
package com.zero.framework.observer
{
	import com.zero.framework.interfaces.IFacade;
	import com.zero.framework.interfaces.INotification;
	import com.zero.framework.interfaces.INotifyResponder;
	
	import flash.utils.Dictionary;

	public class Facade implements IFacade
	{
		public static const ERROR_NOTIFICATION_NOT_SEEN:String = "I've never seen this notification before !";

		// key:消息名	 value:侦听该消息的所有侦听者的array
		private var _observerMap:Dictionary;
		
		// 构造函数
		public function Facade()
		{
			_observerMap = new Dictionary();
		}
		
		/**
		 * 注册该观察者
		 * @param responder
		 * @return  
		 */		
		public function registerResponder(responder:INotifyResponder):Boolean
		{
			var notificationList:Array = responder.notificationList;
			
			// 把所有该观察者侦听的消息都加记录
			for each(var notificationName:String in notificationList)
			{
				var observers:Array = _observerMap[notificationName];
				
				if(observers != null)
				{
					if(observers.indexOf(responder) == -1) observers.push(responder);	
					else throw new Error("重复侦听了消息：" + notificationName);
				}
				else
				{
					_observerMap[notificationName] = [responder];
				}
			}
			return true;
		}
		
		
		
		/**
		 * 发送消息
		 * @param notification 消息名
		 * @param body 消息内容
		 */		
		public function sendNotification(notification:String, body:Object = null):void
		{
			notifyObservers(new Notification(notification, body));
		}
		
		
		/**
		 * 通知所有的观察者
		 * @param notification 
		 */		
		private function notifyObservers(notification:INotification):void
		{
			var observers:Array = _observerMap[notification.getName()];
			if(observers != null)
			{
				// 遍历所有响应改消息的观察者
				for each(var responder:INotifyResponder in observers)
				{
					responder.notifyHandler(notification);
				}
			}
		}
		

	}
}